/**
 * Copyright (c) 2011 The Chromium Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

var content;
var en_attente = "";
var isCtrlPressed = false;
var isQPressed = false;

function readerAssistant() {
    var focused = document.activeElement;
    var selectedText;
    if (focused) {
        try {
          selectedText = focused.value.substring(
              focused.selectionStart, focused.selectionEnd);
        } catch (err) {}
    }
    if (selectedText == undefined) {
        var sel = window.getSelection();
        selectedText = sel.toString();
    }
    if (selectedText != "") {
        if ($('#content_top_for_blind').size() != 0) {
            $('#content_top_for_blind').empty();
            $('#content_top_for_blind').append("<u>Selected text :</u><br/>" + selectedText);
            $('body').css({'position' : 'absolute', 'top' : document.getElementById('content_top_for_blind').offsetHeight + 'px'});
        } else {
            $('body').before('<div id="content_top_for_blind"><u>Selected text :</u><br/>' + selectedText + '</div>');
            $('#content_top_for_blind').css({
                "background-color" : "black",
                "color" : "white",
                "font" : "40px arial bold",
                "padding" : "70px"
            });
            $('body').css({'position' : 'absolute',
                'top' : document.getElementById('content_top_for_blind').offsetHeight + 'px',
                'width' : '100%'
            });
        }
    }
}

function sendMessage() {
    if (isCtrlPressed == true)
    {
            $(this).contents().filter(function() { return this.nodeType == 3
                || this.tagName == "B" || this.tagName == "A" || this.tagName == "STRONG"
                || this.tagName == "U" || this.tagName == "SPAN" || this.tagName == "IMG"
                || this.tagName == "I" || this.tagName == "SUP" || this.tagName == "SUB";}).each(function() {
            var str;
            if (this.tagName == "A") {
                str = $.trim($(this).text());
                str = " . Link : " + str + ".";
            } else if (this.tagName == "IMG") {
                str = $.trim($(this).attr('alt'));
                if (str != "" && str != "undefined")
                    str = " . Image : " + str;
            } else
                str = $.trim($(this).text());                            
            if (str != "") {
                str += " ";
                content += str;
            }
        });
        if (content != "") {
            en_attente = $.trim(content);
            chrome.extension.sendRequest({'can_tts': true}, onExtensionMessage);
        }
        content = "";
    }
}

function onExtensionMessage(request) {
    if (!document.hasFocus()) {
      return;
    }
    if (request['tts_activated'] != undefined) {
        if (request['tts_activated'] == true) {
            chrome.extension.sendRequest({'speak': en_attente});
            en_attente = "";
        }
    } else if (request['helpRead_activated'] != undefined) {
        if (request['helpRead_activated'] == true)
            readerAssistant();
    }
}



function initContentScript() {
    chrome.extension.sendRequest({'init': true}, function(){});
    chrome.extension.onRequest.addListener(onExtensionMessage);
    
    $('*').mouseenter(sendMessage);
    $('b').unbind('mouseenter');
    $('u').unbind('mouseenter');
    $('i').unbind('mouseenter');
    $('sub').unbind('mouseenter');
    $('sup').unbind('mouseenter');
    $('strong').unbind('mouseenter');
    $('span').unbind('mouseenter');
    
    document.addEventListener('mouseup', function() {
        chrome.extension.sendRequest({'can_helpRead': true}, onExtensionMessage);
    });

    document.addEventListener('keydown', function(evt) {
        if (!document.hasFocus()) {
          return true;
        }
        if (evt.keyCode == '17') {
            isCtrlPressed = true;
        }
        if (String.fromCharCode(evt.keyCode) == 'Q') {
            isQPressed = true;
        }
        return true;
    }, false);

    document.addEventListener('keyup', function(evt) {
        if (!document.hasFocus()) {
          return true;
        }
        if (isCtrlPressed && isQPressed) {
             chrome.extension.sendRequest({'tts_button': true}, function(){});
             isCtrlPressed = false;
             isQPressed = false;
             return true;
        }
        if (evt.keyCode == '17') {
            isCtrlPressed = false;
            chrome.extension.sendRequest({'stop_tts': true}, function(){});
        } else if (String.fromCharCode(evt.keyCode) == 'Q') {
            isQPressed = false;
        }
        return true;
    }, false);
}

initContentScript();
